import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/primary_button.dart';

import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/login/application/notifier/login_del_account_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_type_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_update_pwd_notifier.dart';
import 'package:casdon/modules/login/domain/states/del_account_state.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/update_pwd_state.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class VerifyIdentityScreen extends ConsumerStatefulWidget {
  final String account;
  final String? title;

  const VerifyIdentityScreen({super.key, required this.account, this.title});

  @override
  ConsumerState<VerifyIdentityScreen> createState() =>
      _VerifyIdentityScreenState();
}

class _VerifyIdentityScreenState extends ConsumerState<VerifyIdentityScreen> {
  late final ProviderSubscription<DelAccountState> _delAccountSubscription;
  late final ProviderSubscription<UpdatePwdState> _forgetPwdSubscription;

  @override
  void initState() {
    super.initState();
    _setupListeners();
  }

  @override
  void dispose() {
    _forgetPwdSubscription.close();
    _delAccountSubscription.close();
    super.dispose();
  }

  void _setupListeners() {
    _delAccountSubscription = ref.listenManual<DelAccountState>(
      loginDelAccountNotifierProvider,
      (pri, next) => _handleDelAccountState(pri, next),
    );

    _forgetPwdSubscription = ref.listenManual<UpdatePwdState>(
      loginModifyPwdNotifierProvider,
      (pri, next) => _handleUpdatePwdState(pri, next),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonAppBar(title: widget.title ?? "验证身份"),
      body: Container(
        padding: EdgeInsets.all(24),
        color: context.colorScheme.surface,
        child: Column(
          children: [
            SizedBox(height: 10.h),
            Text(
              widget.title == "验证身份" ? "修改密码将通过验证码验证身份" : "注销账户将通过验证码验证身份",
              style: context.textTheme.headlineMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor2,
              ),
            ),
            SizedBox(height: 16.h),
            Text(
              widget.account,
              style: context.textTheme.displayLarge?.copyWith(
                color: context.customColorThemeNonNull.textColor1,
                fontWeight: FontWeight.w400,
              ),
            ),
            SizedBox(height: 48.h),
            PrimaryButton(
              text: "获取验证码",
              onPressed: () => _handleSendVerifyCode(context, ref),
            ),
          ],
        ),
      ),
    );
  }

  void _handleDelAccountState(
    DelAccountState? previous,
    DelAccountState next,
  ) async {
    if (!mounted) return;
    final notifier = ref.read(loginDelAccountNotifierProvider.notifier);
    if (notifier.step == DelAccountStep.sendCode) {
      if (next.source == SendCodeSource.accountPage) {
        if (next.status == CommonNetStatus.success) {
          if (!mounted) return;
          ToastUtil.show(next.message ?? "发送验证码成功");
          CodeInputRoute(
            account: widget.account,
            showBackArrow: true,
          ).push(context);
        } else if (next.status == CommonNetStatus.failure) {
          if (!mounted) return;
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
  }

  _handleUpdatePwdState(UpdatePwdState? pri, UpdatePwdState next) {
    if (!mounted) return;
    final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);

    if (notifier.step == UpdatePwdtep.sendCode) {
      if (next.source == SendCodeSource.accountPage) {
        if (next.status == CommonNetStatus.success) {
          CodeInputRoute(
            account: widget.account,
            showBackArrow: true,
          ).push(context);
        } else if (next.status == CommonNetStatus.failure) {
          ToastUtil.show(next.message ?? "发送验证码失败");
        }
      }
    }
  }

  void _handleSendVerifyCode(BuildContext context, WidgetRef ref) async {
    if (!mounted) return;

    /////////////////////////////////////////////////////
    if (widget.title == "验证身份") {
      ref.read(loginTypeProvider.notifier).state = LoginType.updatePwd;
      final notifier = ref.read(loginModifyPwdNotifierProvider.notifier);
      notifier.updateAccount(widget.account);
      await notifier.sendCode();
    } else {
      ref.read(loginTypeProvider.notifier).state = LoginType.delAccount;
      final notifier = ref.read(loginDelAccountNotifierProvider.notifier);
      notifier.updateAccount(widget.account);
      await notifier.sendCode();
    }
  }
}

extension GoRouterPopN on BuildContext {
  void popTimes(int times) {
    int count = 0;
    // 使用原生 Navigator 的 popUntil 来计数
    Navigator.of(this).popUntil((route) {
      return count++ == times;
    });
  }
}
